﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Touch2Like.Model;
using Touch2Like.DAL;
using Touch2Like.SharedLibrary;

namespace Touch2Like.Web.Customer
{
    public partial class signin : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                KnowledgeDAL knowledge = new KnowledgeDAL();
                KnowledgeInfo knowledgeInfo = knowledge.GetByRandom();

                if (knowledgeInfo != null)
                {
                    lb_KnowledgeTitle.Text = knowledgeInfo.Title;
                    lb_KnowledgeContent.Text = knowledgeInfo.Content;
                }
            }
        }

        protected void btn_Signin_Click(object sender, EventArgs e)
        {
            if (tb_Username.Text.Trim() == "" || tb_Password.Text.Trim() == "")
            {
                lb_Msg.Text = "Invalid username or password.";
                return;
            }

            UserDAL user = new UserDAL();
            UserInfo info = user.GetUserByNameAndEmail(0, tb_Username.Text.Trim());

            if (info != null)
            {
                if (tb_Password.Text.Trim() == Utility.Encryption.Decrypt(info.Password))
                {
                    WebUtility.UserGUID = info.UserGuid.ToString();
                    WebUtility.Username = info.UserName;
                    if (chk_Rememberme.Checked)
                    {
                        Response.Cookies["CAMINTEL"]["USERNAME"] = tb_Username.Text.Trim();
                        Response.Cookies["CAMINTEL"]["PW"] = Utility.Encryption.Encrypt(tb_Password.Text.Trim());
                        Response.Cookies["CAMINTEL"].Expires = DateTime.Now.AddDays(1);
                    }
                    if (!string.IsNullOrEmpty(Request["next"]))
                    {
                        Response.Redirect("/customer/Index.aspx");
                        //Response.Redirect(Server.UrlDecode(Request["next"]));
                    }
                    else
                    {
                        //Response.Redirect("/customer/profile.aspx");
                        Response.Redirect("/customer/Index.aspx");
                    }
                    return;
                }
                else
                {
                    lb_Msg.Text = "Password does not match.";
                }
            }
            else
            {
                lb_Msg.Text = "User does not exist.";
            }

            
        }
    }
}